package storage;

/**
 *@author Adam
 */


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ConnectSocket {


	private int my_backlog = 5;
	private ServerSocket my_serverSocket;
	Socket socket;
	String aboutService;
	String RMIName;
	String myAddress = "";
	int port = -1;
	boolean keepListening = true;


	public ConnectSocket(int a_port, String myRMIName, String mySize) {
		RMIName = myRMIName;
		try{
			InetAddress thisIp =InetAddress.getLocalHost();
			myAddress = thisIp.getHostAddress();
		} catch (Exception e){
			e.printStackTrace();
		}
		connectUp(a_port);
	}

	public void connectUp(int myPort){
		try {
			port = myPort;
			my_serverSocket = new ServerSocket(myPort, my_backlog);
			System.out.println("TCP socket listening on port " + myPort);
		} catch (BindException be){
//			be.printStackTrace();
			System.out.println("port " + myPort + " is in use, trying next");
			myPort++;
			connectUp(myPort);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (SecurityException se) {
			se.printStackTrace();
		}
		System.out.println("port we're using for " + RMIName + " = " + port);
	}


	public int getPort(){
		return port;
	}

	public void close(){
		keepListening = false;
	}

	public void listen() {

		while (keepListening == true) {
			try {
				socket = my_serverSocket.accept();
				BufferedReader in = new BufferedReader(new InputStreamReader(socket
						.getInputStream()));
				String msg = in.readLine();
				if (msg.equals("alive") == false){
					System.out.println("Recceived message: " + msg);
				}
				PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
				String response = parse(msg);
				out.println(response);
				in.close();
				out.close();
				socket.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			} catch (SecurityException se) {
				se.printStackTrace();
			}
		}
//		try{
//		my_serverSocket.close();
//		socket.close();
//		} catch (Exception e){
//		e.printStackTrace();
//		}

	}	

	public String parse(String incoming){
		if (incoming.equals("<Helo>Details</Helo>")){
			System.out.println("replying with RMIName = " + RMIName + " and address = " + myAddress);
			return RMIName + "," + myAddress + "," + "none";
		}
		return "hi server, i dont understand your message";
	}

	public void run(){
		System.out.println("gonna start listening now!!!");
		listen();
	} 

}